package cn.turboinfo.fuyang.api.domain.mini.usecase.file;

import cn.turboinfo.fuyang.api.domain.common.usecase.AbstractUseCase;
import cn.turboinfo.fuyang.api.domain.web.component.file.FileAttachmentHelper;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLConnection;

/**
 * 查看附件
 *
 * @author hai
 */
@Slf4j
@RequiredArgsConstructor
@Component
public class MiniViewFileAttachmentUseCase extends AbstractUseCase<MiniViewFileAttachmentUseCase.InputData, MiniViewFileAttachmentUseCase.OutputData> {

    private final FileAttachmentHelper fileAttachmentHelper;

    @Override
    protected OutputData doAction(InputData inputData) {

        HttpServletResponse response = inputData.getResponse();

        File file = fileAttachmentHelper.readFileAttachment(inputData.fileAttachmentId);
        try (InputStream is = new FileInputStream(file);
             OutputStream os = response.getOutputStream()) {
            response.setContentType(URLConnection.guessContentTypeFromName(file.getName()));
            IOUtils.copy(is, os);
            os.flush();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }


        return OutputData.builder()
                .build();
    }

    @EqualsAndHashCode(callSuper = true)
    @Data
    @NoArgsConstructor(force = true)
    @AllArgsConstructor
    @Builder
    public static class InputData extends AbstractUseCase.InputData {

        /**
         * 附件编码
         */
        private Long fileAttachmentId;

        @NonNull
        private HttpServletResponse response;

    }

    @Getter
    @Setter
    @Builder
    public static class OutputData extends AbstractUseCase.OutputData {

    }
}
